package com.springboot.prac.prac03_algorithm.queue;

/**
 * 循环队列
 */
public class RepeatQueue {
    // 数组
    private int[] array;

    // 队列头
    private int head;

    // 队列尾
    private int rear;

    public RepeatQueue(int capacity) {
        this.array = new int[capacity];
    }

    /**
     * 入队
     * 队尾指针指向的位置永远空出1位，所以队列最大容量比数组长度小1
     */
    public void enQueue(int data) throws Exception {
        if ((rear + 1) % array.length == head) {
            throw new Exception("队列已满！");
        }

        array[rear] = data;
        rear = (rear + 1) % array.length;
    }

    /**
     * 出列
     */
    public int deQueue() throws Exception {
        if (head == rear) {
            throw new Exception("队列已空！");
        }
        int deQueueElement = array[head];
        head = (head + 1) % array.length;
        return deQueueElement;
    }

    public void output() {
        for (int i = head; i != rear; i = (i + 1) % array.length) {
            System.out.println(array[i]);
        }
    }

    public static void main(String[] args) throws Exception {
        RepeatQueue queue = new RepeatQueue(5);
        queue.enQueue(1);
        queue.enQueue(2);
        queue.enQueue(3);
        queue.enQueue(4);
        queue.deQueue();
        queue.output();
    }
}